<?php

namespace app\api\controller\v1;

use app\api\model\Manager as ManagerModel;
use app\api\validate\Manager as ManagerValidate;
use Firebase\JWT\JWT;
use think\Db;
use think\facade\Validate;
use think\Request;

class Manager extends Base
{
    /**
     * 显示用户列表
     *
     * @return \think\Response
     */
    public function index()
    {
       if(empty($this->pageNum) || empty($this->pageSize)){
           return $this->out([],'请填写参数',400);
       }

       $data = Db::name('manager')
             ->alias('m')
             ->join('role r','m.role_id  =  r.role_id')
             ->field('m.mg_id as id,m.mg_name as username,m.mg_mobile as mobile,m.mg_email as email,
             m.mg_time as create_time,m.mg_state,r.role_name')
             ->page($this->pageNum,$this->pageSize)
             ->select();

       if(empty($data)){
           return $this->out([],'无数据','400');
       }

       return $this->out($data,'请求成功','200');

    }

    /**
     * 新增用户
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = Request()->param();

        if(empty($data['username']) || empty($data['password'])){
            return $this->out([],'请输入参数',400);
        }

        $res = [
            'mg_name'      =>  $data['username'],
            'mg_pwd'       =>  $data['password'],
            'mg_email'     =>  $data['email'],
            'mg_mobile'    =>  $data['mobile'],
            'mg_time'      =>  time()
         ];

        $validate = new ManagerValidate;

        if(!$validate->scene('save')->check($res)){
            return $this->out([],$validate->getError(),422);
        }

        //密码加密

        $res['mg_pwd']  =  md5('hch'.sha1($data['password']).'hch');

        $result = ManagerModel::create($res);

        $id = $result->mg_id;

        if(empty($id)){
            return $this->out([],'添加失败',400);
        }

        $user = Db::name('manager')
                ->alias('m')
                ->join('user u','u.username = m.mg_name')
                ->where('m.mg_id',$id)
                ->field('m.mg_id as id,m.mg_name as username,m.mg_mobile as mobile,m.mg_state as type,
                u.qq_open_id as openid,m.mg_email as email,m.mg_time as create_time,u.is_active as is_active')
                ->select();

        return $this->out($user,'添加成功',201);
    }

    /**
     * 根据id查找用户
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
       if(!Validate::isInteger($id)){
           return $this->out([],'id参数错误',422);
       }

       $result = ManagerModel::where('mg_id',$id)
               ->field('mg_id as id,mg_name as username,role_id,mg_email as email,mg_mobile as mobile')
               ->find();

       if(empty($result)){
           return $this->out($result,'查询失败',400);
       }

       return $this->out($result,'查询成功',200);
    }

    /**
     * 编辑用户提交
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
       $data = Request()->param();

       if(!Validate::isInteger($id)){
           return $this->out([],'id参数错误',422);
       }

       $validate = new ManagerValidate;

       $res = [
           'mg_mobile'  =>  $data['mobile'],
           'mg_email'   =>  $data['email']
       ];

       if(!$validate->scene('Update')->check($res)){
           return $this->out([],$validate->getError(),422);
       }

       $user = ManagerModel::where('mg_id',$id)->update($res);

       if(empty($user)){
           return $this->out([],'提交的参数和原先一致',400);
       }

       $result = ManagerModel::where('mg_id',$id)
            ->field('mg_id as id,role_id as rid,mg_name as username,mg_mobile as mobile,mg_email as email,mg_state')
            ->find();

       if(empty($result)){
           return $this->out([],'更新失败',500);
       }

       return $this->out($result,'更新成功',200);
    }

    /**
     * 删除指定用户
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if(!Validate::isInteger($id)){
            return $this->out([],'id参数错误',422);
        }

        $user = ManagerModel::find($id);

        if(empty($user)){
            return $this->out([],'当前id不存在或已被删除',400);
        }

        $res = ManagerModel::get($id)->delete();

        dump($res);

        if($res === true){
            return $this->out([],'删除成功',204);
        }

        return $this->out([],'删除失败',400);
    }


    //用户登录
    public function login(Request $request)
    {
        $data = request()->param();

        $validate = new ManagerValidate;

        $user = [
            'mg_name'  =>  $data['username'],
            'mg_pwd'   =>  $data['password']
        ];

        if(!$validate->scene('Login')->check($user)){
            return $this->out([],$validate->getError(),422);
        }

        $password =  md5('hch'.sha1($data['password']).'hch');

        $where = [
            'mg_name'   =>   $data['username'],
            'mg_pwd'   =>    $password
        ];

        $res = ManagerModel::where($where)->field('mg_id,mg_name,role_id,mg_mobile,mg_email')->find();

        if(empty($res)){
            return $this->out([],'登录失败','400');
        }

        $secret = "electricity";      //密匙

        $payload = [
            'exp'      =>   time()+3600*24,       //过期时间(官方字段:非必需)
            'admin_id' =>   $res['mg_id'],       //自定义字段id
            'admin'    =>   true,                //自定义字段
         ];

        $token = JWT::encode($payload,$secret,'HS256');

        $res['token'] = $token;

        return $this->out($res,'登录成功','200');
    }

    //分配用户角色
    public function role(Request $request,$id)
    {
        $data = request()->param('rid');

        if(!Validate::isInteger($id)){
            return $this->out([],'id参数有误',422);
        }

        $validate = new ManagerValidate;

        $res = [
            'role_id'  =>  $data
        ];

        if(!$validate->scene('role')->check($res)){
            return $this->out([],$validate->getError(),422);
        }

        $user = ManagerModel::where('mg_id',$id)->update($res);

        if(empty($user)){
            return $this->out([],'提交的参数和原先一致',400);
        }

        $result = ManagerModel::where('mg_id',$id)
            ->field('mg_id as id,role_id as rid,mg_name as username,mg_mobile as mobile,mg_email as email')
            ->find();

        if(empty($result)){
            return $this->out([],'设置角色失败',400);
        }

        return $this->out($result,'设置角色成功',200);
    }

}
